import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/../'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keepback.settings')
import django
django.setup()

from home.models import CommunityPost
from elasticsearch import Elasticsearch

es = Elasticsearch(['http://localhost:9200'])

# 可选：重建 community_posts_hot 索引，确保 content 字段为 text 类型
INDEX_NAME = 'community_posts'
def recreate_index():
    if es.indices.exists(index=INDEX_NAME):
        es.indices.delete(index=INDEX_NAME)
    es.indices.create(
        index=INDEX_NAME,
        body={
            "mappings": {
                "properties": {
                    "id":      { "type": "integer" },
                    "title":   { "type": "text" },
                    "content": { "type": "text" },
                    "duration":{ "type": "keyword" },
                    "pace":    { "type": "keyword" },
                    "calorie": { "type": "keyword" },
                    "created_at": { "type": "date", "format": "yyyy-MM-dd'T'HH:mm:ss||yyyy-MM-dd HH:mm:ss||yyyy-MM-dd" },
                    "user_username": { "type": "text" },
                    "user_avatar":   { "type": "keyword" }
                }
            }
        }
    )
    print("已重建 community_posts_hot 索引")

def sync_posts():
    posts = CommunityPost.objects.select_related('user').all()
    for post in posts:
        doc = {
            "id": post.id,
            "title": post.title,
            "content": post.content,
            "duration": post.duration,
            "pace": post.pace,
            "calorie": post.calorie,
            "created_at": post.created_at.strftime('%Y-%m-%dT%H:%M:%S') if post.created_at else None,
            "user_username": getattr(post.user, "nickname", None) or getattr(post.user, "phone", "") or "",
            "user_avatar": post.user.avatar if hasattr(post.user, "avatar") else ""
        }
        es.index(index=INDEX_NAME, id=post.id, document=doc)
    print(f"已同步 {posts.count()} 条社区动态到 ES")

if __name__ == "__main__":
    recreate_index()
    sync_posts()